package org.stvd.common.security.filter.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;

/**
 * 处理OAuth 中用户授权确认的逻辑
 * 这在grant_type 为 authorization_code, implicit 会使用到
 */
public class OauthUserApprovalHandler extends TokenStoreUserApprovalHandler {

    
    public OauthUserApprovalHandler() {
        // Do nothing
    }


    @Override
    public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
            Authentication userAuthentication) {
        
        /*
         * 验证用户是否有访问客户端的权限
         * 比如：客户端的权限：ROLE_CLIENT，ROLE_UNITY，则用户必须拥有其中的一个角色才可以访问
         */
//        boolean hasAuth = false;
//        if(StringsUtil.isEmpty(authorizationRequest.getAuthorities())) {
//            System.out.println("warning: AuthorizationRequest.getAuthorities()为空默认放行所由角色请求！");
//            hasAuth = true;
//        }else {
//            for(GrantedAuthority clientAuth : authorizationRequest.getAuthorities()){
//                for(GrantedAuthority userAuth : userAuthentication.getAuthorities()){
//                    if(clientAuth.getAuthority().equals(userAuth.getAuthority())){
//                        hasAuth = true;
//                    }
//                }
//            }
//        }
//        if(!hasAuth){
//            throw new UserDeniedAuthorizationException("User denied access");
//        }
        
        return super.checkForPreApproval(authorizationRequest, userAuthentication);
    }


    /**
     * 这儿扩展了默认的逻辑, 若 OauthClientDetails 中的 trusted 字段为true, 将会自动跳过 授权流程
     *
     * @param authorizationRequest AuthorizationRequest
     * @param userAuthentication   Authentication
     * @return True is approved
     */
    public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
        if (super.isApproved(authorizationRequest, userAuthentication)) {
            return true;
        }
        if (!userAuthentication.isAuthenticated()) {
            return false;
        }

        return false;
    }

}
